package com.hech.hmall.aspect;

import com.hech.hmall.constant.HttpConstants;
import com.hech.hmall.entity.UserEntity;
import com.hech.hmall.util.TokenHelper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 韩家丰
 * @date 2021/5/3 16:18
 * @desc todo
 */
@Aspect
@Component
@Slf4j
public class TokenAspect {

    /**
     * token工具类
     */
    private final TokenHelper tokenHelper;

    public TokenAspect(TokenHelper tokenHelper) {
        this.tokenHelper = tokenHelper;
    }

    /**
     * 切点
     */
    @Pointcut("@annotation(com.hech.hmall.annotation.TokenRequired)")
    public void annotationPointcut() {
    }

    /**
     * 检查请求中是否包含token,不包含或者token校验不通过抛出异常
     *
     * @param joinPoint 连接点
     * @return 执行
     * @throws Throwable 异常
     */
    @Around("annotationPointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader(HttpConstants.ACCESS_TOKEN);
        UserEntity userEntity = tokenHelper.verifyToken(token);
        Object[] args = joinPoint.getArgs();
        if (args != null && args.length != 0 && args[args.length - 1] instanceof UserEntity) {
            args[args.length - 1] = userEntity;
        }
        return joinPoint.proceed(args);
    }
}
